package com.cwt_taxi_xa;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.util.AppLog;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CrashHandler implements UncaughtExceptionHandler{

	private static final String TAG = "CrashHandler.";
	private Context context;
	private PendingIntent restartIntent;

	public CrashHandler(Context context) {
		// TODO Auto-generated constructor stub
		this.context = context;
	}

	@Override
	public void uncaughtException(Thread thread, final Throwable ex) {
		// TODO Auto-generated method stub
		saveTxt(AppLog.generateTag());
		saveTxt(ex.getLocalizedMessage());
		saveTxt(ex.getMessage());
		saveTxt(exception(ex));

		AppLog.savelog(
				"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+
						AppLog.generateTag()+
						"\n"+ex.getLocalizedMessage()+
						"\n"+ex.getMessage()+
						"\n"+exception(ex)+
						"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
		);

//		Log.e("CrashHandler", "未被处理的异常:"+ex.getLocalizedMessage());
//		Log.e("CrashHandler", "未被处理的异常:"+ex.getMessage());
		if(ex == null){
//			Log.e("CrashHandler", "未被处理的异常ex == null");
//			Thread.getDefaultUncaughtExceptionHandler().uncaughtException(thread, ex);
		}else{
//			Log.e("CrashHandler", ex.getMessage());
//			new Thread(){
//				public void run() {
//					try {
//						Looper.prepare();
//						//						NetworkHandler.showToast("系统因未知原因崩溃，即将重启！");
//						context.stopService(new Intent(context,SerialPortService.class));
//						showDialog();
//						Looper.loop();
//					} catch (Exception e) {
//						// TODO Auto-generated catch block
//						AppLog.e(ExceptionUtil.getInfo(e), e);
//						e.printStackTrace();
//					}
//				}
//			}.start();
//			try {
//				Thread.sleep(2000);
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				AppLog.e(ExceptionUtil.getInfo(e), e);
//				AppLog.e(ExceptionUtil.getInfo(e), e);
//			}
//			AppLog.e(TAG+":"+ExceptionUtil.getInfo((Exception)ex), ex.toString());
		}
		restartSystem();
	}

	File f;
	FileOutputStream fos;
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	int lngMin = 0;
	int lngMax = 0;
	int latMin = 0;
	int latMax = 0;
	public void saveTxt(String str){
		try {
			if(f==null){

				File fs = new File("/mnt/sdcard/");
				File[] fss = fs.listFiles();
				for (int i = 0; i < fss.length; i++) {
					if(fss[i].getName().contains("Buglog-") && Constants.CRASH_FILE_DELETE){
						fss[i].delete();
					}
				}

				f = new File("/mnt/sdcard/Buglog-"+new Date().getTime()+".txt");
				fos = new FileOutputStream(f);
			}
			fos.write((str+"\n").getBytes());
			fos.flush();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static String exception(Throwable t){
		if(t == null)
			return null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try{
			t.printStackTrace(new PrintStream(baos));
		}finally{
			try {
				baos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return baos.toString();
	}


	protected void showDialog() {
		// TODO Auto-generated method stub
//		try {
//			if(NetworkHandler.activityContext != null){
//
//				Dialog dialog = new Dialog(NetworkHandler.activityContext);
//				dialog.setCancelable(false);
//				dialog.show();
//				dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
//				Window window = dialog.getWindow();
//				window.setContentView(R.layout.dialog_for_restart);
//			}
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			AppLog.e(ExceptionUtil.getInfo(e), e);
//			e.printStackTrace();
//		}
	}

	protected void restartSystem() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(context,ActivityWaitQD.class);
		// 参数1：包名，参数2：程序入口的activity
		restartIntent = PendingIntent.getActivity(context, 0, intent,
				Intent.FLAG_ACTIVITY_NEW_TASK);
		// 1秒钟后重启应用
		AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		mgr.set(AlarmManager.RTC, System.currentTimeMillis()+500, restartIntent);

		// 关闭当前应用
//		MainApplication.getInstance().finishAll();
		android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(1);
	}

}
